package com.dalei.vds;

import java.io.IOException;
import java.lang.ref.WeakReference;

import com.dalei.vds.environment.CurrentTask;
import com.dalei.vds.soap.DetectionSoapImpl;
import com.dalei.vdserver.shared.model.ErrorCode;
import com.dalei.vdserver.shared.soap.DetectionSoap;
import com.dalei.vdserver.shared.util.StringChecksum;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DetectionActivity extends Activity {

	private static final int MESSAGE_SHOW_PROGRESS_DIALOG = 0x00000000;

	private static final int MESSAGE_DISMISS_PROGRESS_DIALOG = 0x00000001;

	private static final int MESSAGE_SHOW_TOAST = 0x00000002;

	private static final int MESSAGE_CANCEL = 0x00000003;

	private static final int MESSAGE_FINISH = 0x00000004;

	private EditText odometerReadingEdit;

	private Button itemsBtn;

	private Button imagesBtn;

	private EditText notesEdit;

	private Button finishBtn;

	private Button cancelBtn;

	private Dialog dialog;

	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detection);

		handler = new IncomingHandler(this);

		odometerReadingEdit = (EditText) findViewById(R.id.detection_edit_odoread);
		itemsBtn = (Button) findViewById(R.id.detection_btn_olitems);
		imagesBtn = (Button) findViewById(R.id.detection_btn_olimages);
		notesEdit = (EditText) findViewById(R.id.detection_edit_notes);
		finishBtn = (Button) findViewById(R.id.detection_btn_finish);
		cancelBtn = (Button) findViewById(R.id.detection_btn_cancel);

		odometerReadingEdit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String text = s.toString();
				int value = Integer.parseInt(text);
				CurrentTask.setOdometerReading(value);
			}
		});

		itemsBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(DetectionActivity.this,
						OutlineImagesActivity.class);
				startActivity(intent);
			}
		});

		imagesBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(DetectionActivity.this,
						OutlineImagesActivity.class);
				startActivity(intent);
			}
		});

		notesEdit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String text = s.toString();
				if (text.length() > 1024) {
					Context context = getApplicationContext();
					Toast.makeText(context,
							context.getString(R.string.notes_too_long),
							Toast.LENGTH_SHORT).show();
				} else {
					CurrentTask.setNotes(text);
				}
			}
		});

		finishBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Thread thread = new SubmitDetectionResultThread();
				thread.start();
			}
		});

		cancelBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	private static class IncomingHandler extends Handler {

		private WeakReference<DetectionActivity> reference;

		public IncomingHandler(DetectionActivity activity) {
			// TODO Auto-generated constructor stub
			reference = new WeakReference<DetectionActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			DetectionActivity activity = reference.get();

			switch (msg.what) {

			case MESSAGE_SHOW_PROGRESS_DIALOG:
				activity.dialog = ProgressDialog.show(activity, null,
						activity.getString(R.string.waitting));
				break;

			case MESSAGE_DISMISS_PROGRESS_DIALOG:
				if (activity.dialog.isShowing()) {
					activity.dialog.dismiss();
				}
				break;

			case MESSAGE_SHOW_TOAST:
				Toast.makeText(activity, activity.getString(msg.arg1),
						Toast.LENGTH_SHORT).show();
				break;

			case MESSAGE_CANCEL:
				activity.setResult(RESULT_CANCELED);
				activity.finish();
				break;

			case MESSAGE_FINISH:
				activity.setResult(RESULT_OK);
				activity.finish();
				break;

			default:
				break;
			}
		}
	}

	private class SubmitDetectionResultThread extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS_DIALOG);
			if (odometerReadingEdit.getText().length() > 0) {
				String json = null;
				try {
					json = CurrentTask
							.getDetectionResultInJson(DetectionActivity.this);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (json != null) {
					long crc32 = StringChecksum.createChecksum(json);
					DetectionSoap detectionSoap = new DetectionSoapImpl(DetectionActivity.this);
					int result = detectionSoap.saveDetectionResult(json, crc32);
					handler.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);
					if (result > 0) {
						Message msg = handler.obtainMessage();
						msg.what = MESSAGE_SHOW_TOAST;
						msg.arg1 = R.string.successful_submit_detection_result;
						handler.sendMessage(msg);
						handler.sendEmptyMessage(MESSAGE_FINISH);
					} else {
						Message msg = handler.obtainMessage();
						msg.what = MESSAGE_SHOW_TOAST;
						switch (result) {
						case ErrorCode.UNKNOW_ERROR:
							msg.arg1 = R.string.unknow_error;
							break;
							
						case ErrorCode.INTERNAL_ERROR:
							msg.arg1 = R.string.internal_error;
							break;
							
						case ErrorCode.Detection.NULL_JSON:
							msg.arg1 = R.string.null_json;
							break;
							
						case ErrorCode.Detection.CHECKSUM_ERROR:
							msg.arg1 = R.string.checksum_error;
							break;
							
						case ErrorCode.Detection.NULL_DETECTIONRESULT:
							msg.arg1 = R.string.null_detectionresult;
							break;
							
						case ErrorCode.Detection.NULL_INVALID_ITEMS_LIST:
							msg.arg1 = R.string.null_invalid_items_list;
							break;
							
						case ErrorCode.Detection.NULL_IMAGES_MAP:
							msg.arg1 = R.string.null_images_map;
							break;
							
						case ErrorCode.Detection.GET_TASK_FAILED:
							msg.arg1 = R.string.get_task_failed;
							break;
							
						case ErrorCode.Detection.SAVE_LOG_FAILED:
							msg.arg1 = R.string.save_log_failed;
							break;
							
						case ErrorCode.Detection.SAVE_INVALID_ITEMS_FAILED:
							msg.arg1 = R.string.save_invalid_items_failed;
							break;
							
						case ErrorCode.Detection.SAVE_IMAGES_FAILED:
							msg.arg1 = R.string.save_images_failed;
							break;
							
						default:
							msg.arg1 = R.string.default_value;
							break;
						}
						handler.sendMessage(msg);
					}
				} else {
					handler.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);
					Message msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.error;
					handler.sendMessage(msg);
				}
			} else {
				handler.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);
				Message msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.empty_odometer_reading;
				handler.sendMessage(msg);
			}
		}
	}
}
